<?php

namespace App\Models;

use App\Service\Base\Model;
use Illuminate\Support\Str;

class User extends Model
{
    // 用户管理
    protected $table = 'user';

    // 缓存字段，用于搜索绑定的字段
    protected $cacheFields = ["id", "status",];

    // 获取头像
    public function getHeadImgAttribute($value)
    {
        if(empty($value)){
            $domain = env('STYLE_HOST');

            return $domain.'static/noface.jpg';
        }

        return $value;
    }

    // {"id":"","loginname":"登录名","password":"密码","nickname":"昵称","showname":"展示名称","email":"邮箱","activation_key":"未知字段","status":"状态（0-正常 1-禁用 -1删除）","reg_date":"注册时间"}


    //[ 'id', 'loginname', 'password', 'nickname', 'showname', 'email', 'activation_key', 'status', 'reg_date',]


    //array ( 'id' => '$this->getData("id", null, "trim")', 'loginname' => '$this->getData("loginname", null, "trim")', 'password' => '$this->getData("password", null, "trim")', 'nickname' => '$this->getData("nickname", null, "trim")', 'showname' => '$this->getData("showname", null, "trim")', 'email' => '$this->getData("email", null, "trim")', 'activation_key' => '$this->getData("activation_key", null, "trim")', 'status' => '$this->getData("status", null, "trim")', 'reg_date' => '$this->getData("reg_date", null, "trim")', )

    //$id = $this->getData("id", null, 'trim'); $loginname = $this->getData("loginname", null, 'trim'); $password = $this->getData("password", null, 'trim'); $nickname = $this->getData("nickname", null, 'trim'); $showname = $this->getData("showname", null, 'trim'); $email = $this->getData("email", null, 'trim'); $activation_key = $this->getData("activation_key", null, 'trim'); $status = $this->getData("status", null, 'trim'); $reg_date = $this->getData("reg_date", null, 'trim');

    // 获取多条数据（参数只有ids，因为使用in没办法缓存，所以这么操作）
    public function getOneById($id, $fields = ['*'], $pk = 'id')
    {
        if(empty($id)){
            return [];
        }
        // 如果不要缓存 直接查询
        $getOneById = true;
        $is_cache   = $this->is_cache;
        if($is_cache){
            // 如果缓存 则查询缓存
            $args  = compact('id', 'fields', 'pk', 'getOneById');
            $cName = $this->cacheKey('show', $args);
            $info  = $this->cacheClass()->getCache($cName);
            // 检查是否已经绑定
            if($info){
                $this->checkBangShow($info, $cName);
            }
        }

        // 从数据库中查询
        if(empty($info)){
            // 查询
            $info = $this->where($pk, $id)->select($fields)->first();
            $info = is_object($info) ? $info->toArray() : $info;
            if($is_cache){
                $this->addCacheShow($info, $cName, $info);
            }
        }

        // 各种查询后的操作

        // 1、头像
        // 2、认证类型


        return $info;
    }

    // 检查唯一性
    public function checkUser($data, $id = '')
    {

        $where = [];
        // loginname 唯一性
        if(!empty($data['loginname'])){
            $yzwhere = [['loginname', '=', $data['loginname']], ['status', '>=', 0]];
            if($id){
                $where = [['id', '<>', $id]];
            }
            $info = $this->where($where)->where($yzwhere)->first();
            if($info){
                return $this->return_false('loginname_has_exist');
            }
        }

        // email 唯一性
        if(!empty($data['email'])){
            $yzwhere = [['email', '=', $data['email']], ['status', '>=', 0]];
            if($id){
                $where = [['id', '<>', $id]];
            }
            $info = $this->where($where)->where($yzwhere)->first();
            if($info){
                return $this->return_false('email_has_exist');
            }
        }

        // mobile 唯一性
        if(!empty($data['mobile'])){
            $yzwhere = [['mobile', '=', $data['mobile']], ['status', '>=', 0]];
            if($id){
                $where = [['id', '<>', $id]];
            }
            $info = $this->where($where)->where($yzwhere)->first();
            if($info){
                return $this->return_false('mobile_has_exist');
            }
        }

        return $data;
    }

    // 添加验证
    public function checkData($data, $where = [])
    {
        // 随机码
        if($where && empty($data['password'])){
            unset($data['password']);
        } else{
            $salt = Str::random(4);
            if(empty($data['password'])){
                $data['password'] = 123456;
            }
            // 密码
            $data['salt']     = $salt;
            $data['password'] = $this->add_md5($data['password'], $salt);
        }

        return $data;
    }

    // 修改密码
    public function onPassword($id, $password)
    {
        // 查询用户
        $where = ['id' => $id];
        $info  = $this->isCache(true)->oneFind($where);
        if(empty($info)){
            return $this->return_false('user_has_no_exist');
        }

        // 随机码
        $salt = $info['salt'];
        if(empty($salt)){
            $salt = random(4);
        }

        // 修改执行  密码
        $password = $this->add_md5($password, $salt);
        $updata   = ['salt' => $salt, 'password' => $password];
        $result   = $this->where($where)->update($updata);

        // 缓存操作
        $this->deleteCacheShow($info, $updata);

        return $result;
    }

    // 登录
    public function login($username, $password, $loginField = 'loginname')
    {
        // 获取用户信息
        $info = $this->where([$loginField => $username])->first();
        if(empty($info)){
            return $this->return_false('user_has_no_exist');
        }
        if($info->status === -1){
            return $this->return_false('user_has_been_deleted');
        }
        if($info->status === 0){
            return $this->return_false('user_is_disabled');
        }

        //var_dump($this->add_md5($password, $info->salt));
        // 验证密码
        //  英文网站数据来源于以前的数据，已经忘记密码，所以第一次不验证密码
        if($info->salt){
            if(!$this->ckeckPassword($password, $info->salt, $info['password'])){
                return $this->return_false('password_is_wrong');
            }
        }


        // 登录成功
        //$user   = ['id' => $info->id, 'username' => $info->username, 'head_img' => $info->head_img, 'mobile' => $info->mobile, 'last_ip' => $info->last_ip, 'last_time' => $info->last_time,];
        $user   = $info->toArray();
        $updata = ['last_ip' => request()->ip(), 'last_time' => LARAVEL_TIME,];
        // 第一次登录 完善密码
        if(empty($info->salt)){
            $updata['salt']     = random(4);
            $updata['password'] = $this->add_md5($password, $updata['salt']);
        }
        $rst = $this->where('id', $info->id)->update($updata);

        $this->deleteCacheShow($info);

        return $user;
    }


    // 加密密码
    public function add_md5($password, $salt = '')
    {
        return password_hash($password.$salt, PASSWORD_DEFAULT);
    }

    // 解密
    public function ckeckPassword($password, $salt, $hash)
    {
        return password_verify($password.$salt, $hash);
    }


    // 定义验证操作
    public function rules()
    {
        $add = [
            'loginname' => 'required',
            'password'  => 'required',
        ];

        $edit = [
        ];

        $info = [
        ];


        $rule = [
            //'nickname'       => 'required',
            //'showname'       => 'required',
            //'email'          => 'required',
            //'activation_key' => 'required',
            //'reg_date'       => 'required',
            'status' => ['in:-1,0,1,2'],
        ];


        $msg = [
            'id'             => '自编号',
            'loginname'      => '登录名',
            'password'       => '密码',
            'salt'           => '随机字符串',
            'head_img'       => '头像',
            'nickname'       => '昵称',
            'showname'       => '展示名称',
            'email'          => '邮箱',
            'activation_key' => '未知字段',
            'status'         => '状态（0-正常 1-禁用 -1删除）',
            'ctime'          => '注册时间',
            'mtime'          => '时间',
        ];

        return ['rule' => $rule, 'msg' => $msg, 'add' => $add, 'info' => $info];
    }

}
